package org.csu.demo.db.Controller;

import jakarta.servlet.http.HttpSession;
import org.csu.demo.db.domain.Score;
import org.csu.demo.db.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
public class scoreController {
    @Autowired
    private ScoreService scoreService;

    @GetMapping("/scores/{studentId}")
    public String getScoresByStudentId(@PathVariable String studentId, Model model, HttpSession session) {
        if (session.getAttribute("currentUser") == null) {
            return "redirect:/login";
        }
        List<Score> scores = scoreService.getScoresByStudentId(studentId);
        model.addAttribute("scores", scores);
        model.addAttribute("studentId", studentId);
        return "scores";
    }

    @PostMapping("/scores")
    public String addScore(@ModelAttribute Score score, RedirectAttributes redirectAttributes) {
        scoreService.addScore(score);
        redirectAttributes.addFlashAttribute("message", "成绩添加成功");
        return "redirect:/scores/" + score.getStudent_id();
    }

    @PutMapping("/scores/{id}")
    public String updateScore(@PathVariable int id, @ModelAttribute Score score, RedirectAttributes redirectAttributes) {
        score.setId(id);
        scoreService.updateScore(score);
        redirectAttributes.addFlashAttribute("message", "成绩修改成功");
        return "redirect:/scores/" + score.getStudent_id();
    }

    @DeleteMapping("/scores/{id}")
    public String deleteScore(@PathVariable int id, @RequestParam int studentId, RedirectAttributes redirectAttributes) {
        scoreService.deleteScore(id);
        redirectAttributes.addFlashAttribute("message", "成绩删除成功");
        return "redirect:/scores/" + studentId;
    }
}